import { createContext, useContext, useState, ReactNode, useMemo } from 'react';
import { THEME } from '../../consts';

export type ThemeContextType = {
    theme: 'light' | 'dark' | 'os' | string;
    toggleTheme: (str: string) => void;
};

const ThemeContext = createContext<ThemeContextType>({
    theme: localStorage.getItem(THEME) || 'light',
    toggleTheme: () => { },
});

export function ThemeProvider({ children }: { children: ReactNode }) {
    const [theme, setTheme] = useState(localStorage.getItem(THEME) || 'light');

    const toggleTheme = (str: string) => {
        setTheme(str === 'light' ? 'light' : 'dark');
    };

    // 使用 useMemo 避免不必要的对象创建
    const contextValue = useMemo(() => ({
        theme,
        toggleTheme,
    }), [theme]);

    return (
        <ThemeContext.Provider value={contextValue}>
            {children}
        </ThemeContext.Provider>
    );
}

export function useTheme() {
    const context = useContext(ThemeContext);

    if (!context) {
        // 提供更详细的错误信息和使用指导
        throw new Error('useTheme must be used within a ThemeProvider. Ensure that the ThemeProvider component is correctly wrapping the components that use useTheme hook.');
    }

    return context;
}